<template>
  <div class="login">
    <div class="title">短信验证查询</div>
    <div class="c-999 fz-12 mt-10">请使用下单人号码或收货人号码查询</div>
    <van-form @submit="onSubmit" ref="formRef" class="mt-40">
      <van-field
        v-model="phone"
        name="phone"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请输入手机号' }]"
      />
      <van-field
        v-model="code"
        name="code"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请输入验证码' }]"
      >
        <template #button>
          <van-button
            size="small"
            round
            @click="getCode"
            :disabled="codeWaitTime !== 0"
            >{{
              codeWaitTime
                ? `${codeWaitTime} 秒后重试`
                : "获取验证码"
            }}</van-button
          >
        </template>
      </van-field>
      <div class="mt-20">
        <van-button
          round
          block
          color="linear-gradient(to right, #d61a1b, #e2595a)"
          native-type="submit"
        >
          查询
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getCaptcha, verifyCaptcha } from "@/projects/invoice/api/home/index";
import { Toast } from "vant";
import { isPhoneNumber } from "@/projects/invoice/utils";
import { getLocations, setLocations, setPhoneTokenMap } from '@/projects/invoice/utils/storage'

export default {
  data() {
    const orderHistoryPhone = getLocations('orderHistoryPhone');
    return {
      phone: orderHistoryPhone || "",
      code: "",
      codeWaitTime: 0,
    }
  },
  methods: {
    onSubmit() {
      setLocations('orderHistoryPhone', this.phone)
      const params = {
        phone: this.phone,
        captcha: this.code,
        type: "PHONE",
      };
      verifyCaptcha(params).then((res) => {
        if (res.code === 200) {
          const phoneTokenMap = {
            [this.phone]: res.data
          }
          setPhoneTokenMap(phoneTokenMap)
          this.$emit('verify')
        } else {
          Toast.fail(res.msg);
        }
      });
    },
    // 获取验证码
    getCode() {
      if (!isPhoneNumber(this.phone)) {
        Toast.fail("请输入正确的手机号！");
        return;
      }
      if (this.phone) {
        const params = {
          phone: this.phone,
        };
        getCaptcha(params).then((res) => {
          this.codeWaitTime = 60;
          this.codeTimer = setInterval(() => {
            this.codeWaitTime--;
            if (this.codeWaitTime === 0) {
              this.codeTimer && clearInterval(this.codeTimer);
              this.codeTimer = null;
            }
          }, 1000);
        });
      } else {
        Toast("请输入手机号");
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  padding: 40px 20px;
  .title {
    font-size: 26px;
  }
}
</style>
